package com.example.forum.interceptor;

import com.example.forum.annotation.LoginRequired;
import com.example.forum.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
    拦截带有@LoginRequired注解的方法,检查登录状态
 */
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {
    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取方法上是否有LoginRequired注解
        if(hostHolder.getUser()!=null){ //用户已经登录，任何方法都可以访问
            return true;
        }
        //用户没有登录，判断访问的方法是否需要拦截
        if(handler instanceof HandlerMethod){   //拦截到的是一个方法
            HandlerMethod method=(HandlerMethod) handler;
            LoginRequired annotation = method.getMethodAnnotation(LoginRequired.class);
            if(annotation==null){   //该方法上没有LoginRequired注解
                return true;
            }
        }
        //没有登录，并且方法上有LoginRequired注解时，拦截该请求,并跳转到登录页面
        response.sendRedirect(request.getContextPath()+"login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
